package com.bwie.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.unit.MobileMessageUtil;
import com.bwie.unit.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("Code/{mobile}")
    public R Code(@PathVariable String mobile){
        //验证码超过1分失效
        Long expire = stringRedisTemplate.getExpire("mobile" + mobile);
        if (expire>1){
            return R.ERROR(500,"验证码已经失效");
        }
        //获取验证码
        String code = RandomUtil.randomNumbers(4);
        MobileMessageUtil.sendMobileMessage(mobile,code);
        stringRedisTemplate.opsForValue().set("mobile"+mobile,code,1, TimeUnit.MINUTES);
        return R.OK(code);
    }

    @PostMapping("login")
    public R login(@RequestBody User user){
        //判断用户名是否正确
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User userLogin = userService.getOne(wrapper);
        if (userLogin == null){
            return R.ERROR(500,"账号错误");
        }

        //判断手机号是否正确
        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(User::getMobile,user.getMobile());
        User mobile = userService.getOne(wrapper1);
        if (mobile == null){
            return R.ERROR(500,"手机号错误");
        }

        //判断验证是否正确
        String s = stringRedisTemplate.opsForValue().get("mobile"+user.getMobile());
        String code = user.getCode();
        if (!s.equals(code)){
            return R.ERROR(500,"验证码错误");
        }

        //获取token
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",userLogin.getId());
        String token = Jwts.builder().setClaims(map).signWith(SignatureAlgorithm.HS256, "bwie").compact();
        map.put("token",token);
        //将token存入redis中
        stringRedisTemplate.opsForValue().set("token"+userLogin.getId(),token,20,TimeUnit.MINUTES);
        return R.OK(map);
    }

}
